package com.bdqn.t320.controller;

import com.alibaba.fastjson.JSON;
import com.bdqn.t320.pojo.Attach;
import com.bdqn.t320.pojo.Page;
import com.bdqn.t320.pojo.Role;
import com.bdqn.t320.pojo.SysUser;
import com.bdqn.t320.service.RoleService;
import com.bdqn.t320.service.SysUserService;
import com.bdqn.t320.service.SysUserServiceImp;
import com.bdqn.t320.util.GUID;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.util.*;

@Controller
@RequestMapping("/user")
public class UserController {

    private static Logger logger = Logger.getLogger(UserController.class);

    @Resource
    SysUserService sysUserService;
    @Resource
    RoleService roleService;

    @RequestMapping("/getUserList")
    public String getUserList(Model model,
                              @RequestParam(value = "userName", required = false) String userName,
                              @RequestParam(value = "userRole", required = false, defaultValue = "0") Integer userRole,
                              @RequestParam(value = "pageIndex", defaultValue = "1") String pageIndex) {
        System.out.println("getUserList");
        SysUser sysUser = new SysUser();
        sysUser.setUserName(userName);
        sysUser.setUserRole(userRole);

        Page page = new Page();
        page.setCurrentPage(Integer.parseInt(pageIndex));
        List<SysUser> userList = sysUserService.getUserListBiz(page, sysUser);
        Integer count = sysUserService.getCountBiz(sysUser);
        //设置总记录数的同时会计算好总页数
        page.setTotalRecord(count);
        page.setList(userList);

        List<Role> roleList = roleService.getRoleListBiz();

        model.addAttribute("page", page);
        model.addAttribute("userName", userName);
        model.addAttribute("userRole", userRole);
        model.addAttribute("pageIndex", pageIndex);
        model.addAttribute("roleList", roleList);
        return "sysUser/list";
    }

    @RequestMapping("/toAdd")
    public String getUserList() {
        return "sysUser/add";
    }

    @RequestMapping("/add")
    public String add(Model model, SysUser sysUser, HttpSession session, HttpServletRequest request,
                      @RequestParam(value = "idPic", required = false) MultipartFile idPic) {
        boolean bool = false;

        int uid = (int) (Math.random() * 100000);
        logger.info("uid:" + uid);
        SysUser user = (SysUser) session.getAttribute("sysUser");
        sysUser.setId(uid);
        sysUser.setCreatedBy(user.getId());
        sysUser.setCreationDate(new Date());
        Attach attach = null;

        //判断附件是否为空
        if (!idPic.isEmpty()) {
            String path = request.getSession().getServletContext().getRealPath("statics" + File.separator + "uploadfiles");
            //String path = "D://img";
            logger.info("上传文件路径:" + path);
            //获取源文件名
            String originalFile = idPic.getOriginalFilename();
            logger.info("上传文件名称:" + originalFile);
            int saveSize = (int) idPic.getSize();
            String suff = originalFile.substring(originalFile.indexOf(".") + 1, originalFile.length());
            logger.info("上传文件名后缀:" + originalFile);
            //int fileSize = 500000;
            File targetFile = new File(path);
            //判断路径是否存在,如果不存在就创建
            if (!targetFile.exists()) {
                targetFile.mkdirs();
            }
            try {
                GUID guid = new GUID();
                String saveName = guid.toString();
                idPic.transferTo(new File(targetFile, saveName + "." + suff));
                attach = new Attach();
                attach.setFid(uid);
                attach.setEnable(1);
                attach.setSaveUrl(path);
                attach.setRealName(originalFile);
                attach.setSuff(suff);
                attach.setSaveName(saveName);
                attach.setSaveSize(saveSize);
                attach.setUserId(user.getId());
                attach.setSavetime(new Date());
                attach.setPx(1);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        bool = sysUserService.addUserAttach(sysUser, attach);
        if (bool) {
            return "redirect:/user/getUserList";
        } else {
            return "sysUser/add";
        }
    }


    @RequestMapping("/view")
    public String view(Model model, Integer id) {
        SysUser sysUser = sysUserService.viewBiz(id);
        model.addAttribute("sysUser", sysUser);
        return "sysUser/view";
    }

    //http://localhost:8080/ch11/user/find/24
    @ResponseBody
    @GetMapping(value = "/{id}/find")
    public Object find(Model model, @PathVariable Integer id) {
        System.out.println("find");
        SysUser sysUser = sysUserService.viewBiz(id);
        //model.addAttribute("sysUser", sysUser);
        //return JSON.toJSONString(sysUser);
        return sysUser;
    }

    @PostMapping("/{id}/find")
    public String finda(Model model, @PathVariable Integer id) {
        System.out.println("find");
        SysUser sysUser = sysUserService.viewBiz(id);
        model.addAttribute("sysUser", sysUser);
        return "sysUser/view";
    }

    @ResponseBody
    @RequestMapping("/userCodeExist")
    public Object userCodeExist(Model model, String userCode) {
        System.out.println("view");
        int count = sysUserService.userCodeExistBiz(userCode);
        Map<String, String> map = new HashMap<>();
        if (count > 0) {
            map.put("account", "exist");
        } else {
            map.put("account", "noexist");
        }
        return map;
    }

    @ResponseBody
    @GetMapping(value = "/deleteById")
    public Object deleteById(Model model, Integer id) {
        int count = sysUserService.deleteByIdBiz(id);
        Map<String, String> map = new HashMap<>();
        if (count > 0) {
            map.put("delResult", "true");
        } else {
            map.put("delResult", "false");
        }
        return map;
    }

    //跳转到update.jsp
    @RequestMapping("/toupdate")
    public String toUpdate(int id, Model model) {
        //根据id去查询记录
        SysUser user = sysUserService.viewBiz(id);
        model.addAttribute("user", user);
        return "sysUser/update";
    }

    @RequestMapping(value = "update", method = RequestMethod.POST)
    public String update(SysUser user, HttpSession session) {
        SysUser sessionUser = (SysUser) session.getAttribute("sysUser");
        //设置修改用户的id
        user.setModifyBy(sessionUser.getId());
        //获取当前时间并设置修改时间为当前时间
        user.setModifyDate(new Date());
        int count = sysUserService.updateBiz(user);
        if (count > 0) {
            return "redirect:/user/getUserList";
        } else {
            return "sysUser/update";
        }
    }

    /**
     * ajax获取角色列表
     *
     * @return
     */
    //produces = {"application/json;charset=UTF-8"}只能解决ajax返回的字符编码问题
    @ResponseBody  //ajax需要添加注解
    @RequestMapping(value = "getrolelist", produces = {"application/json;charset=UTF-8"})
    public Object getRoleList() {
        List<Role> roleList = roleService.getRoleListBiz();
        return roleList;
    }

    @RequestMapping(value = "/sys")
    public String sys() {
        logger.info("功能还未实现,请自行实现...");
        return "sys";
    }
}
